package zheezes.protocol.impl.gbw;

import zheezes.util.ByteUtil;

public class DataUnitId implements Comparable<DataUnitId> {
	public static final int SIZE = 4;
	
	protected short pn = 0;
	protected short fn;
	
	public DataUnitId(short pn, short fn) {
		this.pn = pn;
		this.fn = fn;
	}

	public DataUnitId() {
		String name = getClass().getSimpleName().toLowerCase();
		StringBuilder sb = new StringBuilder();
		int idx = -1;
		if ((idx = name.indexOf("down")) > 0) {
			idx += 4;
		} else if ((idx = name.indexOf("up")) > 0) {
			idx += 2;
		}
		char c = '\0';
		if (idx++ > 0) {
			while (Character.isDigit((c = name.charAt(idx++)))) {
				sb.append(c);
			}
			fn = (short) Integer.parseInt(sb.toString());
		}
	}
	
	public static final short[] parse(byte[] buf, int offset) {
		int idx = offset;
		short pn = (short) 0xFFFF;
		if (buf[idx] == 0x00 && buf[idx + 1] == 0x00) {
			pn = 0;
		} else {
			pn = (short) (8 * ByteUtil.ffs(buf[idx + 1]) + ByteUtil.ffs(buf[idx]) + 1);
		}
		idx += 2;
		short fn = (short) (8 * buf[idx + 1] + ByteUtil.ffs(buf[idx]) + 1);
		idx += 2;
		
		return new short[] { pn, fn };
	}
	
	public int sizeof() {
		return SIZE;
	}
	
	public int setBytes(byte[] buf, int offset, int max) {
		short[] id = parse(buf, offset);
		pn = id[0];
		fn = id[1];
		
		return sizeof();
	}

	public int getBytes(byte[] buf, int offset) {
		int idx = offset;
		if (pn == 0) {
			buf[idx++] = 0x00;
			buf[idx++] = 0x00;
		} else {
			buf[idx++] = (byte) (0x01 << ((pn + 7) % 8)); // da1
			buf[idx++] = (byte) (0x01 << (pn / 8));       // da2
		}
		buf[idx++] = (byte) (0x01 << ((fn + 7) % 8)); // dt1
		buf[idx++] = (byte) ((fn - 1) / 8);			  // dt2

		return idx - offset;
	}
	
	public int compareTo(DataUnitId other) {
		if (pn != other.pn) {
			return pn - other.pn;
		} else {
			return fn - other.fn;
		}
	}
	
	public byte getAfn() {
		Class clazz = getClass();
		String name = clazz.getName();
		int idx = name.indexOf("Afn");
		return ByteUtil.cctoa(name.toCharArray(), idx + 3);
	}

	public short getPn() {
		return pn;
	}

	public void setPn(short pn) {
		this.pn = pn;
	}

	public short getFn() {
		return fn;
	}

	public void setFn(short fn) {
		this.fn = fn;
	}
}
